<?php

/*
采购订单列表
*/
namespace Modules\Purchasing\Http\Repositories;

use App\Services\UnitService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Purchasing\Models\Provisional;
use Modules\Purchasing\Models\Provisionalschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Purchasing\Models\Supplier;
use Modules\Purchasing\Models\Supplierschedule;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use Modules\Warehouse\Models\Storagelocation;
use Modules\Purchasing\Models\Inspectionlist;
use Modules\Purchasing\Models\Inspectionlistcheck;
use Modules\Purchasing\Models\Inspectionlisttable;
use extend\services\warehouse\{warehouseService};//引入自定义类
use Modules\Base\Models\Material;
use Modules\Inspection\Models\Inspection;
class InspectionlistReget
{
    
    /*
    检验单列表接口
    */
    public static function listtable($data = [])
    {
        return self::getBuildertable($data)->paginate($data['limit'] ?? 20);
    }

    /*
    检验id
    */
    public static function getBuildertable(array $data = []): Builder
    {
        $builder = Inspectionlisttable::query();


        if (isset($data['inspectionnumber'])) {
            $builder->where('inspectionnumber',$data['inspectionnumber']);
        }

        if (isset($data['state'])) {
            $builder->where('state',$data['state']);
        }

        //查物料编码 
        if (isset($data['fmaterialid'])) {

            $fmaterialid = Purchaseorderschedule::select('fmaterialid','id')->where('fmaterialid', 'like', "%{$data['fmaterialid']}%")->get()->toArray();
            $fmaterial_id = [];
            foreach($fmaterialid as $k=>$v){
                $fmaterial_id[] = $v['id'];
            }

            $Provisionalschedule = Provisionalschedule::select('purchaseorderschedule_id','provisional_id','inspectionlisttable_id')
            ->whereIn('purchaseorderschedule_id',$fmaterial_id)
            ->get()
            ->toArray();

            $inspectionlisttable_id = [];
            foreach($Provisionalschedule as $k=>$v){
                $inspectionlisttable_id[] = $v['inspectionlisttable_id'];
            }
            $inspectionlisttable_id = array_unique($inspectionlisttable_id);
            $builder->whereIn('id',$inspectionlisttable_id);
        }
        
         //采购单号
        if (isset($data['fbillno'])) {

            $fbillno = Purchaseorder::select('fbillno','id')->where('fbillno', 'like', "%{$data['fbillno']}%")->get()->toArray();
            $fmaterial_fbillno = [];
            foreach($fbillno as $k=>$v){
                $fmaterial_fbillno[] = $v['id'];
            }
             $fmaterial_fbillno = array_unique($fmaterial_fbillno);
            $Provisionalschedule = Provisionalschedule::select('purchaseorderschedule_id','provisional_id','inspectionlisttable_id')
            ->whereIn('purchaseorder_id',$fmaterial_fbillno)
            ->get()
            ->toArray();
           
            $inspectionlisttable_id = [];
            foreach($Provisionalschedule as $k=>$v){
                $inspectionlisttable_id[] = $v['inspectionlisttable_id'];
            }
            $inspectionlisttable_id = array_unique($inspectionlisttable_id);
            $builder->whereIn('id',$inspectionlisttable_id);
        }



        
        if (isset($data['decision'])){
            $InspectionlistData = Inspectionlist::select('id')->where('decision',$data['decision'])->get()->toArray();
            $Inspectionlist_id = [];
            foreach($InspectionlistData as $k=>$v){
                $Inspectionlist_id[] = $v['id'];
            }
            $inspectionlisttable_id_data = Provisionalschedule::select('purchaseorderschedule_id','provisional_id','inspectionlist_id','inspectionlisttable_id')
            ->whereIn('inspectionlist_id',$Inspectionlist_id)
            ->get()
            ->toArray();
            $inspectionlisttable_idres = [];
            foreach($inspectionlisttable_id_data as $k=>$v){
                $inspectionlisttable_idres[] = $v['inspectionlisttable_id'];
            }
            $builder->whereIn('id',$inspectionlisttable_idres);
        }


        //不合格退货单
        if (isset($data['inspectionresult'])) {

            $InspectionlistData = Inspectionlist::select('id')->where('inspectionresult',$data['inspectionresult'])->get()->toArray();
            $Inspectionlist_id = [];
            foreach($InspectionlistData as $k=>$v){
                $Inspectionlist_id[] = $v['id'];
            }

            $inspectionlisttable_id_data = Provisionalschedule::select('purchaseorderschedule_id','provisional_id','inspectionlist_id','inspectionlisttable_id')
            ->whereIn('inspectionlist_id',$Inspectionlist_id)
            ->get()
            ->toArray();
            $inspectionlisttable_idres = [];
            foreach($inspectionlisttable_id_data as $k=>$v){
                $inspectionlisttable_idres[] = $v['inspectionlisttable_id'];
            }
            $builder->whereIn('id',$inspectionlisttable_idres);

        }
        
        


        $builder->orderBy('id', 'desc');
        return $builder;
  
    }


    /*
    数据列表
    */
    public static function list($data = [])
    {

        return self::getBuilder($data)->paginate($data['per_page'] ?? 20);
        
    }

     /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilder(array $data = []): Builder
    {
            
      

            //品号
        if (isset($data['fmaterialid'])||isset($data['fmaterialname'])||isset($data['fmaterialmodel'])) {
            $purchaseorderschedule_id=[];
            $purchaseorderschedule = purchaseorderschedule::query()->select('id');
          
            //品名
            if (isset($data['fmaterialid'])) {
                $purchaseorderschedule->where('fmaterialid',$data['fmaterialid']);
            }
            //品名
            if (isset($data['fmaterialname'])) {
                $purchaseorderschedule->where('fmaterialname',$data['fmaterialname']);
            }
            //规格
            if (isset($data['fmaterialmodel'])) {
                $purchaseorderschedule->where('fmaterialmodel',$data['fmaterialmodel']);
            }
            $purchaseorderschedule = $purchaseorderschedule->get();
           
            $supplier_id_data = [];
            foreach($purchaseorderschedule as $k=>$v){
                $purchaseorderschedule_id[] = $v['id'];
            }
          
            $supplier_id = supplierschedule::select('id','supplier_id')->whereIn('purchaseorderschedule_id',$purchaseorderschedule_id)->get();
            $supplier_id_data = [];
            foreach($supplier_id as $k=>$v){
                $supplier_id_data[] = $v['supplier_id'];
            }

           
       
            // $supplier_id = provisionalschedule::select('id')->whereIn('supplier_id',$supplier_id_data)->get();
            // $supplierId = [17];
            // return $supplier_id;
            // foreach($supplier_id as $k=>$v){
            //     $supplierId[] = $v['id'];
            // }
        }
        
      
        $builder = Inspectionlist::query();
        $builder->select(
            'inspectionlist.id',
            'inspectionlist.inspectionnumber',
             'inspectionlist.quantityincoming',
             'inspectionlist.inspectiontime',
             'inspectionlist.method',
             'inspectionlist.gitquantity',
             'inspectionlist.inspectionresult',
             'inspectionlist.decision',
             'inspectionlist.inspector_user',
             'inspectionlist.state',
             'inspectionlist.unit',
             'inspectionlist.auditor_user',
             'inspectionlist.audittime',
             'inspectionlist.created_at',
             'inspectionlist.updated_at',
             'provisional.ordernumber',
             'provisionalschedule.supplierschedule_id',
             'provisionalschedule.barcode',
             'provisionalschedule.quantityreceived',
             'supplier.supplierOrder',
             'purchaseorder.fbillno',
             'purchaseorder.fsupplierid_number',
             'purchaseorder.fsupplierid_name',
        );
        $builder->join('provisionalschedule as provisionalschedule', 'provisionalschedule.inspectionlist_id', '=', 'inspectionlist.id');
        $builder->join('provisional as provisional', 'provisional.id', '=', 'provisionalschedule.provisional_id');
        $builder->join('supplier as supplier', 'supplier.id', '=', 'provisionalschedule.supplier_id');
        $builder->join('purchaseorder as purchaseorder', 'purchaseorder.id', '=', 'provisionalschedule.purchaseorder_id');

           //检验单列表id
        if (isset($data['ifid'])) {
            $resid = Provisionalschedule::select('inspectionlist_id')->where('inspectionlisttable_id',$data['ifid'])->get();
            $inspectionlist_id = [];
            foreach($resid as $k=>$v){
                $inspectionlist_id[] = $v['inspectionlist_id'];
            }
            $builder->where('inspectionlist.id',$inspectionlist_id);
        }


        if (isset($data['fmaterialid'])||isset($data['fmaterialname'])||isset($data['fmaterialmodel'])) {
            $builder->whereIn('provisionalschedule.supplier_id', $supplier_id_data);
        }

         //送货单
        if (isset($data['supplierOrder'])) {
            $builder->where('supplier.supplierOrder', 'like', "%{$data['supplierOrder']}%");
        }
        //送货单
        if (isset($data['supplierOrder'])) {
            $builder->where('supplier.supplierOrder', 'like', "%{$data['supplierOrder']}%");
        }
         //暂收单
        if (isset($data['ordernumber'])) {
            $builder->where('provisional.ordernumber', 'like', "%{$data['ordernumber']}%");
        }

        //批号
        if (isset($data['barcode'])) {
            $builder->where('provisionalschedule.barcode', 'like', "%{$data['barcode']}%");
        }

        //供应商代号
        if (isset($data['fsupplierid_number'])) {
            $builder->where('purchaseorder.fsupplierid_number', 'like', "%{$data['fsupplierid_number']}%");
        }
         //供应商名称
        if (isset($data['fsupplierid_name'])) {
            $builder->where('purchaseorder.fsupplierid_name', 'like', "%{$data['fsupplierid_name']}%");
        }
         //采购单号
         if (isset($data['fbillno'])) {
            $builder->where('purchaseorder.fbillno', 'like', "%{$data['fbillno']}%");
        }

        if (isset($data['inspectionnumber'])) {
            $builder->where('inspectionlist.inspectionnumber', 'like', "%{$data['inspectionnumber']}%");
        }
        
        if (isset($data['inspectiontime'])) {
            $builder->where('inspectionlist.inspectiontime', strtotime($data['inspectiontime']));
        }

        if (isset($data['inspectionresult'])) {
            $builder->where('inspectionlist.inspectionresult',$data['inspectionresult']);
        }

        if (isset($data['inspector_user'])) {
            $builder->where('inspectionlist.inspector_user',$data['inspector_user']);
        }

        if (isset($data['auditor_user'])) {
            $builder->where('inspectionlist.auditor_user',$data['auditor_user']);
        }

        if (isset($data['state'])) {
            $builder->where('inspectionlist.state',$data['state']);
        }

        $builder->orderBy('inspectionlist.id', 'desc');
        return $builder;
    }

    /*
    数据添加方法
    */
    public static function create(array $data)
    {
   
        $Inspectionlist = new Inspectionlist;
        return self::createOrSave($Inspectionlist, $data);
    }

    //数据添加方法
    public static function createOrSave(Inspectionlist $Inspectionlist,$data)
    {

        //判断是否检完成
        $provisional_id = Provisionalschedule::select('provisional_id')
        ->where('provisional_id',$data['provisional_id'])
        ->groupby(['supplier_id','purchaseorderschedule_id','purchaseorder_id','provisional_id']) 
        ->first()
        ->toArray();

        if(count($data['data']) < count($provisional_id)){
            throw new FailedException('未检验完成为');
        } 

        // $data = [
        //     'id'=>55,
        //     'inspectiontime'=>time(),
        //     'method'=>'222',
        //     'quantityincoming'=>'444',
        //     'inspectionresult'=>'55',
        //     'decision'=>'55',
        //     'inspector_user'=>'444',
        // ];

        try {
            //开始起事务
            DB::beginTransaction();

            foreach($data['data'] as $k=>$v){

                $InspectionlistData = [];
                $InspectionlistData['inspectiontime'] = time()  ?? '';
                $InspectionlistData['method'] = $v['method'];
                $InspectionlistData['gitquantity'] = $v['gitquantity'];
                $InspectionlistData['quantityincoming'] = $v['quantityincoming'];
                $InspectionlistData['inspectionresult'] = $v['inspectionresult'];
                $InspectionlistData['decision'] = $v['decision'];
                $InspectionlistData['inspector_user'] = $data['creator_id'];
                $insertGetId = Inspectionlist::insertGetId($InspectionlistData);
                // $Inspectionlist->fill($InspectionlistData);
                // $Inspectionlist->save();

                foreach($v['detailscheck_all'] as $ka=>$va){
                    $v['detailscheck_all'][$ka]['inspectionlist_id'] = $insertGetId;
                }
                // $Inspectionlist->detailscheckAll()->createMany($v['detailscheck_all']);
                $Inspectionlistcheck_id = Inspectionlistcheck::insert($v['detailscheck_all']);
                $Provisionalschedule = Provisionalschedule::query()->where('id',$v['id'])->update(['inspectionlist_id'=> $insertGetId]); 

                // $Provisionalschedule = Provisionalschedule::query()->updateOrCreate(['id' => $v['id']], [
                //     'inspectionlist_id'       => $Inspectionlist['id']
                // ]); 

            }
            
            // $Inspectionlisttable = Inspectionlisttable::query()->updateOrCreate(['id' => $data['inspectionlisttable_id']], [
            //     'state' => 1
            // ]);

            DB::commit();
            return ['code'=>1000,'message'=>'检验成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('数据添加失败，服务器上火星了请联系技术处理');
        }
    }


    //修改
    public static function createUpdate($data)
    {

        // $dataRes = Inspectionlist::where('id',$data['inspectionlist_id'])->first();
        $dataRes = Inspectionlist::select('id')->where('id',$data['id'])->first();
        if(empty($dataRes)){
           throw new FailedException('参数值出错');
        }

        try {
            //开始起事务
            DB::beginTransaction();
                $Inspectionlist = Inspectionlist::where('id',$dataRes->id)->update(
                    ['decision'=>$data['decision']
                ]);
                // foreach ($data['data'] as $k=>$v){
                //     $Inspectionlist = Inspectionlist::query()->updateOrCreate(['id' => $v['inspectionlist_id']], [
                //         'inspectiontime'       => time()  ?? '',
                //         'method'       => $v['method']  ?? '',
                //         'gitquantity'       => $v['gitquantity']  ?? '',
                //         'quantityincoming'       => $v['quantityincoming']  ?? '',
                //         'inspectionresult'       => $v['inspectionresult']  ?? '',
                //         'decision'       => $v['decision']  ?? 0,
                //         'inspector_user'       => $data['creator_id']  ?? '',
                //     ]);
                //     $Inspectionlist->detailscheckAll()->createMany($v['detailscheck_all']);  
                // }

            DB::commit();
            return ['code'=>1000,'message'=>'检验成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }

    }


     //添加接口
     public static function Dataadditiondate($data)
     {

        // $data = [
        //     'inspectiontime'=>time(),
        //     'method'=>'222',
        //     'quantityincoming'=>'444',
        //     'inspectionresult'=>'55',
        //     'decision'=>'55',
        //     'inspector_user'=>'444',
        // ];
       
 
         try {
             //开始起事务
             DB::beginTransaction();

             $Inspectionlist = Inspectionlist::query();

             $Inspectionlist = [];
             $Inspectionlist['inspectiontime'] = time()  ?? '';
             $Inspectionlist['method'] = $data['method'];
             $Inspectionlist['gitquantity'] = $data['gitquantity'];
             $Inspectionlist['quantityincoming'] = $data['quantityincoming'];
             $Inspectionlist['inspectionresult'] = $data['inspectionresult'];
             $Inspectionlist['decision'] = $data['decision'];
             $Inspectionlist['inspector_user'] = $data['inspector_user'];
             $Inspectionlist->fill($Inspectionlist);

             $Inspectionlist->save();
              Inspectionlist::query()->where('id',$data['id'])->update(['inspectionlist_id'=>$Inspectionlist['id']]);
              foreach($data['detailscheck_all'] as $k=>$v){
                $data['detailscheck_all'][$K]['inspectionlist_id'] = $Inspectionlist['id'];
              }
              
             $Inspectionlist->detailscheckAll()->createMany($data['detailscheck_all']);  
             

            //$Inspectionlist = Inspectionlist::query()->updateOrCreate(['id' => $v['inspectionlist_id']], [
            //     'inspectiontime'       => time()  ?? '',
            //     'method'       => $v['method']  ?? '',
            //     'gitquantity'       => $v['gitquantity']  ?? '',
            //     'quantityincoming'       => $v['quantityincoming']  ?? '',
            //     'inspectionresult'       => $v['inspectionresult']  ?? '',
            //     'decision'       => $v['decision']  ?? 0,
            //     'inspector_user'       => $data['creator_id']  ?? '',
            //]);

             DB::commit();
             return ['code'=>1000,'message'=>'检验成功'];
         } catch (\Exception $e) {
             DB::rollBack();
             throw new FailedException('服务器飞出地球了请联系技术找回');
         }
 
     }



    /**
     * 查询一条数据
     *
     */
    public static function find($id)
    {
        return Provisional::query()->with('detailscheckAll')->find($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
            Provisional::query()->where('id',$id)->delete();
            Provisionalschedule::query()->where('provisional_id',$id)->delete();
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
           throw new FailedException('服务器飞出地球了请联系技术找回');
        }


    }
     /**检验单审核
     * @param $id
     * @return void
     */
    public static function auditupdate($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
                Inspectionlist::query()->updateOrCreate(['id' => $id], [
                    'state' => 1,
                ]); 
            DB::commit();
            return $data=['code'=>1000,'message'=>'审核成功'];
            
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }


    /**
     * @param $id
     * @return void
     */
    public static function showApi($id)
    {

        if(empty($id)||$id=='undefined'){
            return ['code'=>1000,'message'=>'请求成功','data'=>[]]; 
        }
           $data = Provisionalschedule::query()
           ->select(
            'provisional.ordernumber',
            'provisionalschedule.id',
            'provisionalschedule.provisional_id',
            'provisionalschedule.purchaseorder_id',
            'provisionalschedule.supplier_id',
            'provisionalschedule.purchaseorderschedule_id',
            'provisionalschedule.supplierschedule_id',
            'provisionalschedule.quantityreceived',
            'provisionalschedule.barcode',
            'provisionalschedule.storagelocation',
            'provisionalschedule.inspectionlist_id',
            'inspectionlist.inspectionnumber',
            'inspectionlist.quantityincoming',
            'inspectionlist.inspectiontime',
            'inspectionlist.method',
            'inspectionlist.gitquantity',
            'inspectionlist.inspectionresult',
            'inspectionlist.decision',
            'inspectionlist.inspector_user',
            'inspectionlist.state',
            'inspectionlist.unit',
            'inspectionlist.auditor_user',
            'inspectionlist.audittime',
            )
            ->join('provisional as provisional', 'provisional.id', '=', 'provisionalschedule.provisional_id')
            ->join('inspectionlist as inspectionlist', 'inspectionlist.id', '=', 'provisionalschedule.inspectionlist_id')
            ->where('inspectionlist.id',$id)
            ->where('provisionalschedule.inspectionlist_id',$id)
            ->first();
            if(empty($data)){
                return ['code'=>1000,'message'=>'请求成功','data'=>[]]; 
            }

            //检验明细
            $Inspectionlistcheck = Inspectionlistcheck::query()
            ->select(
                'inspection.inspectionnumber',
                'inspection.productname',
                'inspectioncheck.testitem',
                'inspectioncheck.testmethod',
                'inspectioncheck.teststandard',
                'inspectioncheck.remarks',
                'inspectionlistcheck.remarks',
                'inspectionlistcheck.remarks as inspeCheckRemarks',
                'inspectionlistcheck.imgurl',
                )
            ->where('inspectionlistcheck.inspectionlist_id',$id)
            ->join('inspectioncheck as inspectioncheck', 'inspectioncheck.id', '=', 'inspectionlistcheck.inspectioncheck_id')
            ->join('inspection as inspection', 'inspection.id', '=', 'inspectioncheck.inspection_id')
            ->get();
          

            foreach($Inspectionlistcheck as $k=>$v){
                 
                $fnumber = Material::
                            select('id','fnumber','fname','fspecification','funit_number','funit_name')
                            ->whereIn('id',[375])
                            ->get()->toArray();
                
                            
                if(!empty($fnumber)){
                        $name ='';
                    foreach($fnumber as $ks=>$vs){
                        $name .= $vs['fnumber'].'、';
                    }
                    $Inspectionlistcheck[$k]['productname'] = rtrim($name,'、');
                }else{
                    $Inspectionlistcheck[$k]['productname'] = '共用方案';
                }
            }
            $data['Inspectionlistcheck'] = $Inspectionlistcheck;
            $Supplierschedule = Supplierschedule::select(
                'supplier.supplierOrder',
                'supplierschedule.purchaseorder_id',
                'supplierschedule.purchaseorderschedule_id'
                )
            ->join('supplier as supplier', 'supplier.id', '=', 'supplierschedule.supplier_id')
            ->where('supplier.id',$data['supplier_id'])
            ->where('supplierschedule.purchaseorderschedule_id',$data['purchaseorderschedule_id'])
            ->where('supplierschedule.purchaseorder_id',$data['purchaseorder_id'])
            ->first();
            $data['supplierOrder']=$Supplierschedule['supplierOrder'];
        
            
            $Purchaseorderschedule = Purchaseorderschedule::select(
                'purchaseorder.fbillno',
                'purchaseorder.fsupplierid_number',
                'purchaseorder.fsupplierid_name',
                'purchaseorderschedule.fmaterialid',
                'purchaseorderschedule.fmaterialname',
                'purchaseorderschedule.fmaterialmodel',
                'purchaseorderschedule.fmodel',
                'purchaseorderschedule.funitid_name',
                )
                ->join('purchaseorder as purchaseorder', 'purchaseorder.id', '=', 'purchaseorderschedule.purchaseorder_id')
                ->where('purchaseorder.id',$data['purchaseorder_id'])
                ->where('purchaseorderschedule.id',$Supplierschedule['purchaseorderschedule_id'])
                ->first();
            $data['fbillno'] = $Purchaseorderschedule['fbillno'];
            $data['fsupplierid_number'] = $Purchaseorderschedule['fsupplierid_number'];
            $data['fsupplierid_name'] = $Purchaseorderschedule['fsupplierid_name'];
            $data['fmaterialid'] = $Purchaseorderschedule['fmaterialid'];
            $data['fmaterialname'] = $Purchaseorderschedule['fmaterialname'];
            $data['fmaterialmodel'] = $Purchaseorderschedule['fmaterialmodel'];
            $data['fmodel'] = $Purchaseorderschedule['fmodel'];
            $data['funitid_name'] = $Purchaseorderschedule['funitid_name'];

            $data['inspectionresult'] = $data['inspectionresult'] == 1?'不合格':'合格';

            $kingDeeService = new warehouseService();
            $datauser = $kingDeeService->uerdata();
            $data['phone'] =  isset($data['inspector_user'])?$datauser[$data['inspector_user']]['phone']:'';
            $data['inspector_user'] =  isset($data['inspector_user'])?$datauser[$data['inspector_user']]['username']:'';
            $data['auditor_user'] =  isset($data['auditor_user'])?$datauser[$data['auditor_user']]['username']:'';

             return ['code'=>1000,'message'=>'扫描成功','data'=>$data];

    }


    
    /*检验单接口
     * @param $id
     * @return void
     */
    public static function checkPdaApi($code,$data)
    {
      
        $data = Provisionalschedule::select(
            'provisional.ordernumber',
            'provisionalschedule.id',
            'provisionalschedule.provisional_id',
            'provisionalschedule.purchaseorder_id',
            'provisionalschedule.supplier_id',
            'provisionalschedule.supplierschedule_id',
            'provisionalschedule.purchaseorderschedule_id',
            'provisionalschedule.quantityreceived',
            'provisionalschedule.barcode',
            'provisionalschedule.storagelocation',
            'provisionalschedule.inspectionlist_id',
            'provisionalschedule.inspectionlisttable_id',
            )
            ->join('provisional as provisional', 'provisional.id', '=', 'provisionalschedule.provisional_id')
            ->where('provisionalschedule.barcode',$code)
            //->where('provisionalschedule.inspectionlisttable_id',$data['id'])
            ->first();
            if(empty($data)) throw new FailedException('扫描出错,该箱号条码不属于这张单'); 
            
            $state = 0;
            $stateCode = 0;
            $Inspectionlisttable = Inspectionlisttable::select('id','inspectionnumber','state')->where('id',$data['inspectionlisttable_id'])->first();
           if(!empty($Inspectionlisttable)){
               if($Inspectionlisttable['state']==1){
                   $state = 1;
               }
               
           }


            
            //已扫描过的箱号
            if(!empty($data['inspectionlist_id'])){
                
                $stateCode = 1;
                // throw new FailedException('亲！该箱号检验过，无需重复检验哦'); 
                // $Inspectionlist_data = Inspectionlist::select(
                //     'quantityincoming',
                //     'inspectiontime',
                //     'method',
                //     'gitquantity',
                //     'inspectionquantity',
                //     'goodquantity',
                //     'defectivequantity',
                //     'scrapquantity',
                //     'inspectionresult',
                //     'decision',
                //     'inspector_user',
                //     'state',
                //     'remarks',
                //     'id',
                //     )->first();
                //   $Inspectionlistcheck_data  = Inspectionlistcheck::select('inspectionlist_id','inspectioncheck_id','remarks','imgurl')->where('inspectionlist_id',$Inspectionlist_data['id'])->get()->toArray();

                //   if(!empty($Inspectionlistcheck_data)){
                //         foreach($Inspectionlistcheck_data as $k=>$v){
                //              $Inspectioncheck_data = Inspectioncheck::where('id',$v['inspectioncheck_id'])->first();
                //              $inspection_data = inspection::where('id',$Inspectioncheck_data['inspection_id'])->first();
                //              $Inspectioncheck_data['imgUrl'] = $v['imgurl'];
                //              $Inspectioncheck_data['productname'] = $inspection_data['productname'];
                //              $Inspectionlist_data['detailscheck_all'] = $Inspectioncheck_data;
                //         }
                //   }
                //   $data['inspectionlist_data'] = $Inspectionlist_data;
            }
            // p($data);
            // exit;
            

            // try {
            //     //开始起事务
            //     DB::beginTransaction();   

                $data['quantityincoming'] = $data['quantityreceived'];//来料数量
                $data['gitquantity'] = $data['gitquantity'];//送检数量

                $data['inspectionresult'] = 1;//0不合格1合格
                $data['decision'] = 1;//0不合格1合格

                $Supplierschedule = Supplierschedule::select(
                    'supplier.supplierOrder',
                    'supplierschedule.purchaseorder_id',
                    'supplierschedule.purchaseorderschedule_id'
                    )
                ->join('supplier as supplier', 'supplier.id', '=', 'supplierschedule.supplier_id')
                ->where('supplier.id',$data['supplier_id'])
                ->where('supplierschedule.purchaseorderschedule_id',$data['purchaseorderschedule_id'])
                ->where('supplierschedule.purchaseorder_id',$data['purchaseorder_id'])
                ->first();

                if(empty($Supplierschedule)) throw new FailedException('暂收单数据出错');
                $data['supplierOrder']=$Supplierschedule['supplierOrder'];
             
                $Purchaseorderschedule = Purchaseorderschedule::select(
                    'purchaseorder.fbillno',
                    'purchaseorder.fsupplierid_number',
                    'purchaseorder.fsupplierid_name',
                    'purchaseorderschedule.fmaterialid',
                    'purchaseorderschedule.fmaterialname',
                    'purchaseorderschedule.fmaterialmodel',
                    'purchaseorderschedule.fmodel',
                    'purchaseorderschedule.funitid_name',
                    )
                ->join('purchaseorder as purchaseorder', 'purchaseorder.id', '=', 'purchaseorderschedule.purchaseorder_id')
                ->where('purchaseorder.id',$data['purchaseorder_id'])
                ->where('purchaseorderschedule.id',$Supplierschedule['purchaseorderschedule_id'])
                ->first();

                if(empty($Supplierschedule)) throw new FailedException('物料信息出错');
             
                $data['fbillno'] = $Purchaseorderschedule['fbillno'];
                $data['fsupplierid_number'] = $Purchaseorderschedule['fsupplierid_number'];
                $data['fsupplierid_name'] = $Purchaseorderschedule['fsupplierid_name'];
                $data['fmaterialid'] = $Purchaseorderschedule['fmaterialid'];
                
                $inspection = Db::table('inspection')->select('completecheck')->where('id',$Purchaseorderschedule['fmaterialid'])->first();
                
                if(!empty($inspection)){
                    $data['method'] = $inspection->completecheck;//0抽检1全检
                }else{
                    $data['method'] = 0;
                }
                
                $data['fmaterialname'] = $Purchaseorderschedule['fmaterialname'];
                $data['fmaterialmodel'] = $Purchaseorderschedule['fmaterialmodel'];
                $data['fmodel'] = $Purchaseorderschedule['fmodel'];
                $data['funitid_name'] = $Purchaseorderschedule['funitid_name'];
                $data['state'] = $state;
                $data['stateCode'] = $stateCode;
                $data['inspectionnumber'] = $Inspectionlisttable['inspectionnumber'];
              
                return ['code'=>1000,'message'=>'扫描成功','data'=>$data];

                // DB::commit();
                // return '扫描成功';
                // } catch (\Exception $e) {
                // DB::rollBack();
                // throw new FailedException('服务器飞出地球了请联系技术找回');
                // }
        
    }


  
    /*检验单整单验证接口
     * @param $id
     * @return void
     */
    public static function checksingledata($id)
    {
   
        
        try {
            //开始起事务
            DB::beginTransaction();
        
          //判断是否检完成
          $provisional_id = Provisionalschedule::select('provisional_id','purchaseorder_id','purchaseorderschedule_id','supplier_id','inspectionlisttable_id')
          ->where('inspectionlisttable_id',$id)
          ->groupby(['supplier_id','purchaseorderschedule_id','purchaseorder_id','provisional_id','inspectionlisttable_id']) 
          ->get()
          ->toArray();
         
     
          foreach($provisional_id as $k=>$v){
              
              $fmaterialid = Purchaseorderschedule::select('fmaterialid')->where('id',$v['purchaseorderschedule_id'])
              ->where('purchaseorder_id',$v['purchaseorder_id'])
              ->first();
            
                
                
             $Material_id = Material::select('id')->where('fnumber',$fmaterialid['fmaterialid'])->first();
             
              $Inspection = '';
              
              if(!empty($Material_id)){
                  //判断物料是否抽检还是全检
                  $Inspection = Inspection::select('productname','completecheck')->where('productname', 'like', "%{$Material_id['id']}%")->first();
              }
              
             
             if(empty($Inspection)){
                  $Inspection = Inspection::select('productname','completecheck')->where('inspectionnumber','A2429693')->first();
             }
            
             if($Inspection['completecheck']==1){
                  //1.全检
                  $inspectionlist_id = Provisionalschedule::select('inspectionlist_id')
                  ->where('supplier_id',$v['supplier_id'])
                  ->where('purchaseorderschedule_id',$v['purchaseorderschedule_id'])
                  ->where('purchaseorder_id',$v['purchaseorder_id'])
                  ->where('provisional_id',$v['provisional_id'])
                  ->where('inspectionlisttable_id',$v['inspectionlisttable_id'])
                  ->where('inspectionlist_id',null)
                  ->first();
                
                  if(!empty($inspectionlist_id)){
                 
                      $fmaterialid = Purchaseorderschedule::select('fmaterialid')->where('id',$v['purchaseorderschedule_id'])
                      ->where('purchaseorder_id',$v['purchaseorder_id'])
                      ->first();
                      
                            
                      return throw new FailedException('未检验完成为,未检验品号：'.$fmaterialid['fmaterialid']);
                  }
  
             }else{
                  //2.抽检
                  $inspectionlist_id = Provisionalschedule::select('inspectionlist_id','id')
                  ->where('supplier_id',$v['supplier_id'])
                  ->where('purchaseorderschedule_id',$v['purchaseorderschedule_id'])
                  ->where('purchaseorder_id',$v['purchaseorder_id'])
                  ->where('provisional_id',$v['provisional_id'])
                  ->where('inspectionlisttable_id',$v['inspectionlisttable_id'])
                  ->whereNotNull('inspectionlist_id')
                  ->first();
                  
                 
                  if(empty($inspectionlist_id)){
                      $fmaterialid = Purchaseorderschedule::select('fmaterialid')->where('id',$v['purchaseorderschedule_id'])
                      ->first();
                      return throw new FailedException('未检验完成为,未检验品号：'.$fmaterialid['fmaterialid']);
                  }
             }
             
          }
         
            
         Inspectionlisttable::where('id',$id)->update([ 'state' => 1,'creator_id'=> UnitService::getUserId()]);
           DB::commit();
          return ['code'=>1000,'message'=>'检验成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }





}
